<template>
  <div class="addScheduling-page">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item>路边停车</el-breadcrumb-item>
      <el-breadcrumb-item>收费员管理</el-breadcrumb-item>
      <el-breadcrumb-item>编辑收费员排班表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- <breadcrumb /> -->
    <div class="add-component">
      <div>
        <div class="row">
          <div class="page-title">编辑收费员排班表</div>
          <div class="submit-btns">
            <el-popover
              placement="bottom"
              title=""
              :width="200"
              :visible="historyDateSelect"
            >
              <template #reference>
                <el-button
                  type="primary"
                  class="submit-btn-import"
                  @click="historyDateSelect = true"
                >
                  <img class="icon-img" alt="" />导入历史排班</el-button
                >
              </template>
              <div>
                <el-date-picker
                  v-model="params.historyDate"
                  type="date"
                  placeholder="选择日期"
                  style="width: 100%"
                  :disabled-date="disabledDate"
                />
                <div style="display: flex; justify-content: space-between">
                  <div @click="importHistoryData">确定</div>
                  <div @click="historyDateSelect = false">取消</div>
                </div>
              </div>
            </el-popover>
            <el-popover
              placement="bottom"
              title=""
              :width="200"
              :visible="changeDateSelect"
            >
              <template #reference>
                <el-button
                  type="primary"
                  class="submit-btn-date"
                  @click="changeDateSelect = true"
                >
                  <img class="icon-img" alt="" />切换日期</el-button
                >
              </template>
              <div>
                <el-date-picker
                  v-model="params.curDate"
                  type="date"
                  placeholder="选择日期"
                  style="width: 100%"
                />
                <div style="display: flex; justify-content: space-between">
                  <div @click="changeData">确定</div>
                  <div @click="changeDateSelect = false">取消</div>
                </div>
              </div>
            </el-popover>
          </div>
        </div>
        <div class="page-detial">
          <div>
            班组名称:<span>{{ list.teamName }}</span>
          </div>
          <div>
            日期:<span>{{ list.date }}</span>
          </div>
          <div>
            星期:<span>{{ list.week }}</span>
          </div>
        </div>
        <div
          class="submit-btns"
          style="margin-top: 60px; display: flex; align-items: center"
        >
          <div class="page-title">排班明细</div>
          <el-select
            style="width: 125px; margin-left: 20px"
            placeholder="请选择排班类型"
            @change="setFilterTableData"
            v-model="params.shift"
          >
            <el-option label="全部" value="-1"></el-option>
            <el-option
              v-for="item in shiftList.data"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </div>
      </div>
      <div class="schedule-table">
        <ul class="table-header">
          <li
            v-for="v in tableHeader"
            :key="v.key"
            :style="{ width: v.width, flex: v.width ? 'unset' : '1' }"
          >
            {{ v.title }}
          </li>
        </ul>
        <ul class="table-body">
          <li v-for="v in filterTableData">
            <div
              v-for="(vv, i) in tableHeader"
              :key="vv.key"
              class="body-li-item"
              :style="{ width: vv.width, flex: vv.width ? 'unset' : '1' }"
            >
              <setTxtByParam
                :data="v"
                :index="i"
                v-model="v.shift"
              ></setTxtByParam>
            </div>
            <div
              class="schedule-bar"
              :style="{ left: barLeftMargin + 'px' }"
              v-if="v.start && v.end"
            >
              <div
                class="path-bar"
                :style="{
                  marginLeft: setMarginLeft(v.start),
                  marginRight: setmarginRight(v.end),
                  backgroundColor: v.color + '30',
                }"
                v-if="v.shift != '1810924151423770646'"
              >
                <selectPath
                  v-model="v.dutySection"
                  :dateTime="list.date"
                  :data="v"
                  :color="v.color"
                  :teamId="list.teamId"
                ></selectPath>
              </div>
            </div>
          </li>
        </ul>
      </div>
      <div class="footer">
        <el-button class="reset-btn" @click="return2Calendar">取 消</el-button>
      </div>
    </div>
  </div>
</template>
<script setup>
import { ref, reactive, h, computed } from "vue";
import selectPath from "@/components/selectPath/index.vue";
import {
  getScheduleList,
  getShiftList,
  setScheduleByHistory,
  editSchedule,
} from "../request.js"
import { getTeamGroup } from "@/service/modules/publicModule";
import { useRoute, useRouter } from "vue-router";
import dayjs from "dayjs";
import { ElMessageBox } from "element-plus";
const route = useRoute();
const router = useRouter();
const tableColumns = 24;
const tableHeader = ref([
  { title: "班次", key: "name", width: "130px" },
  { title: "收费员", key: "cashier", width: "130px" },
]);
const historyDateSelect = ref(false);
const changeDateSelect = ref(false);
// 这里判断一下，如果页面是edit就添加一行
const isAddOrEdit = () => {
  if (true)
    tableHeader.value.unshift({
      title: "操作",
      key: "actions",
      width: "180px",
    });
};
isAddOrEdit();
const params = ref({
  shift: "-1",
  historyDate: null,
  curDate: null,
});
// status：1-绿色   2-蓝色   3-红色
const tableData = ref([
  //   { name: "张三", start: "8.30", end: "18.30", status: 1 },
]);
const filterTableData = ref([]);

const list = ref({
  week: "",
  date: "",
  teamName: "",
});

const shiftList = reactive({
  data: [],
});
const pathData = ref([]);

const barLeftMargin = computed(() => {
  return tableHeader.value.reduce((pre, cur) => {
    return (
      pre + ((cur.width ? cur.width.slice(0, cur.width.length - 2) : 0) - 0)
    );
  }, 0);
});

const disabledDate = (time) => {
  const date = time.getTime();
  const cutoff = new Date(newTime.value).getTime();
  return date > cutoff;
};

const newTime = ref("");

const initData = async (data) => {
  const encryptedParam = decodeURIComponent(route.query.id);
  const decryptedParam = JSON.parse(encryptedParam);
  // console.log("decryptedParam编辑 ===>", decryptedParam);

  list.value.teamId = decryptedParam.teamId;
  list.value.week = decryptedParam.week;
  list.value.date = decryptedParam.date;

  // 获取班组名称
  await getTeamGroup().then((res) => {
    // console.log("res1 ===>", res);
    res.data.result.find((item) => {
      if (item.id === list.value.teamId) {
        list.value.teamName = item.name;
      }
    });
  });

  // 班次选择器
  await getShiftList().then((res) => {
    shiftList.data = res.data.result;
  });

  if (data) {
    tableData.value = [];
    list.value.date = data;
    newTime.value = data;
  } else {
    newTime.value = list.value.date;
  }
  // 班组列表
  await getScheduleList({
    teamId: list.value.teamId,
    dutyDate: newTime.value,
  }).then((res) => {
    tableData.value = res.data.result.map((v) => {
      v.dutySection = v.dutySection ?? [];
      setShilter(v);
      return v;
    });
    // debugger;
    setFilterTableData();
  });

  if (!data) {
    for (let i = 0; i < tableColumns; i++) {
      tableHeader.value.push({
        title: `${i}-${i + 1}`,
        key: `column-${i + 1}`,
      });
    }
  }
};

const setShilter = (data) => {
  const item = shiftList.data.find((v) => v.id === data.shift);
  data.start = item.startTime;
  data.end = item.endTime;
  data.color = item.markColor;
};

const setFilterTableData = () => {
  if (params.value.shift == "-1") filterTableData.value = tableData.value;
  else
    filterTableData.value = tableData.value.filter((v) => {
      return v.shift == params.value.shift;
    });
};
const setTimeRange = (data) => {
  return (val) => {
    const item = shiftList.data.find((v) => {
      return v.id == val;
    });

    if (item.startTime === item.endTime) {
      data.start = item.startTime;
      data.end = item.endTime;
      data.color = item.markColor;
    } else {
      data.start = item.startTime;
      data.end = item.endTime;
      data.color = item.markColor;
    }
  };
};
const setTxtByParam = (props) => {
  let headerItem = tableHeader.value[props.index];
  if (headerItem.key === "name") {
    const arr = [];
    for (let item of shiftList.data) {
      arr.push(h(ElOption, { key: item.id, label: item.name, value: item.id }));
    }
    return h(
      ElSelect,
      {
        ...props,
        style: { width: "80%" },
        placeholder: "请选择排班类型",
        onChange: setTimeRange(props.data),
      },
      {
        default: () => arr,
      }
    );
  } else if (headerItem.key === "actions") {
    return [
      h("div", {
        class: "submit-btn",
        innerHTML: "提交",
        onClick: () => {
          const { cashierId, dutySection, shift } = props.data;

          // const matchedDutySections = pathData.value.filter((item) =>
          //   dutySection.includes(item.id)
          // );
          // console.log("matchedDutySections ===>", matchedDutySections);

          editSchedule({
            id: props.data.id,
            teamId: list.value.teamId,
            dutyDate: list.value.date,
            scheduleInfos: [
              {
                cashier: cashierId,
                shift: shift,
                dutySection: dutySection,
              },
            ],
          }).then((res) => {
            if (res.data.code === 0) {
              ElMessage({
                type: "success",
                message: res.data.result,
              });
              // router.push("/roadsideParking/scheduling");
            } else {
              ElMessage.error(res.data.msg);
            }
          });
        },
      }),
      h("div", {
        class: "reset-btn",
        innerHTML: "清空",
        onClick: () => {
          console.log("props ===>", props);

          ElMessageBox.confirm(
            `确认清空${props.data.cashier}的排班吗?`,
            "温馨提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }
          ).then(() => {
            props.data.shift = null;
            props.data.start = null;
            props.data.end = null;
          });
        },
      }),
    ];
  } else {
    return props.data[headerItem.key] ?? "";
  }
};
const setMarginLeft = (time) => {
  const timeArr = time.split(":");
  // 8.30转化为8.5
  let numbertime = Number(timeArr[0]) + ((timeArr[1] / 60).toFixed(2) - 0);
  return ((numbertime / 24) * 100).toFixed(2) + "%";
};
const setmarginRight = (time) => {
  const timeArr = time.split(":");
  let numbertime = 24 - Number(timeArr[0]) - (timeArr[1] / 60).toFixed(2);
  return ((numbertime / 24) * 100).toFixed(2) + "%";
};
const importHistoryData = () => {
  const _date = dayjs(params.value.historyDate).format("YYYY-MM-DD");
  // console.log("_date ===>", _date);
  // console.log("list.value.date ===>", list.value.date);
  // return;
  ElMessageBox.confirm(`确定导入历史数据${_date}?`, "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      setScheduleByHistory({
        teamId: list.value.teamId,
        dutyDate: list.value.date,
        historyDate: _date,
      }).then((res) => {
        if (res.data.code === 0) {
          ElMessage({
            type: "success",
            message: res.data.result,
          });
          initData(list.value.date);
          // router.push("/roadsideParking/scheduling");
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    })
    .catch(() => {});
};
const changeData = () => {
  const _date = dayjs(params.value.curDate).format("YYYY-MM-DD");
  ElMessageBox.confirm(`此操作将丢失未确认的排班修改,是否继续?`, "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    initData(_date);
  });
};
const return2Calendar = () => {
  router.push("/roadsideParking/scheduling");
};
initData();
</script>
<style lang='less' scoped>
:deep(.submit-btn) {
  background-color: #2986ff;
  font-size: 14px;
  color: #fff;
  width: 60px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

:deep(.reset-btn) {
  border: 1px solid #2986ff;
  font-size: 14px;
  color: #2986ff;
  width: 60px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  margin-left: 10px;
}

.page-detial {
  margin-top: 12px;
  display: flex;
  font-size: 14px;
  color: #666;

  span {
    color: #333;
    margin-left: 20px;
    margin-right: 40px;
  }
}

.add-component {
  margin-top: 16px;
  min-height: 100%;
  padding: 24px;
  background: #fff;
  border-radius: 6px;
  overflow: auto;
}

.row {
  display: flex;
  justify-content: space-between;
}

.submit-btns {
  display: flex;

  .submit-btn-import {
    background: #007aff;
    border: 1px solid #007aff;
    border-radius: 2px;
    margin-left: 12px;
    padding: 5px 16px;
  }

  .submit-btn-date {
    background: #35c362;
    border: 1px solid #35c362;
    border-radius: 2px;
    margin-left: 12px;
    padding: 5px 16px;
  }
}

.schedule-table {
  margin-top: 20px;
  width: 100%;
  height: 80%;
  font-size: 14px;
  min-width: 1200px;

  .table-header {
    background-color: #f4f4f4;
    display: inline-flex;
    width: 100%;
    height: 55px;

    li {
      border: 1px solid #d1d1d1;
      flex: 1;
      border-right: 0;
      display: flex;
      align-items: center;
      justify-content: center;

      &:last-of-type {
        border-right: 1px solid #d1d1d1;
      }
    }
  }

  .table-body {
    display: flex;
    width: 100%;
    flex-direction: column;

    li {
      width: 100%;
      height: 46px;
      display: flex;
      border-bottom: 1px solid #d1d1d1;
      position: relative;

      .schedule-bar {
        position: absolute;
        height: 100%;
        right: 0;
        display: inline-flex;

        .path-bar {
          flex: 1;
          display: flex;
          align-items: center;
          justify-content: center;
          padding: 0 15px;
        }

        .green-bar {
          background-color: #c5eed2;
          color: #27ac51;

          .cicle-icon {
            background-color: rgb(53, 195, 98);
          }
        }

        .blue-bar {
          background-color: #c2dcff;
          color: #007aff;

          .cicle-icon {
            background-color: rgb(0, 122, 255);
          }
        }

        .red-bar {
          background-color: #ffe0dc;
          color: #f32d12;

          .cicle-icon {
            background-color: rgb(243, 45, 18);
          }
        }
      }

      .body-li-item {
        display: inline-flex;
        height: 100%;
        align-items: center;
        justify-content: center;
        border-left: 1px solid #d1d1d1;

        &:last-of-type {
          border-right: 1px solid #d1d1d1;
        }
      }
    }
  }
}

.footer {
  margin-top: 24px;
  width: 100%;
  display: flex;
  flex-direction: row-reverse;
}

.reset-btn {
  width: 65px;
  height: 32px;
  background: #ffffff;
  border-radius: 2px;
  border: 1px solid #d9d9d9;
  font-weight: 400;
  font-size: 14px;
  color: rgba(0, 0, 0, 0.65);
}

.confirm-btn {
  width: 65px;
  height: 32px;
  background: #007aff;
  border-radius: 2px;
  font-weight: 400;
  font-size: 14px;
  color: #ffffff;
  margin-left: 20px;
}

.page-title {
  font-size: 20px;
  color: #333;
}
</style>